package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer { //回显服务器
    private DatagramSocket socket = null;
    public UdpEchoServer(int port) throws SocketException { //port:端口号
        // SocketException:通常表示(scoket)创建失败
        socket = new DatagramSocket(port);//服务器需要手动指定端口
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){ //每次循环都是处理一个请求-响应过程
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            //通过该字节数组保存收到的消息正文,应用层数据报即UDP数据报载荷部分
            socket.receive( requestPacket);//()内是输出型参数(DatagramPacket内部包含一个字节数组)
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //2.根据请求计算响应(此时回显服务器啥都不需要做)
            String response = process(request);
            //3.将响应返回到客户端
            //构造响应对象
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());//得到INetAddress对象(与服务器通信的对端的ip和端口号)
            socket.send(responsePacket);

            //打印日志
            System.out.printf("[%s:%d] req: %s,resp: %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
